<template>
  <div class="return-exchange-reason">
    <header>
      <h2 :class="required ? required : ''">
        <slot />
      </h2>
    </header>
    <section>
      <el-form label-width="100px" label-position="left">
        <el-form-item :label="isExchange ? '换货原因' : '退货原因'">
          <el-select :disabled="!edit" v-model="reason_sel" placeholder="请选择" @change="onChangeReasonSel">
            <el-option v-for="item in return_reason" :key="item.enumKey" :label="item.enumVal" :value="item.enumKey" />
          </el-select>
        </el-form-item>
        <el-form-item label="具体原因">
          <el-input
            :disabled="!edit"
            v-model="reason_text"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 10 }"
            placeholder="请描述具体原因"
            @change="onChangeReasonText"
            maxlength="150"
            show-word-limit
          />
        </el-form-item>
        <el-form-item :label="isExchange ? '换货图片' : '退货图片'">
          <div class="imgs-function">
            <m-upload
              v-if="edit"
              class="dialog-upload"
              action="string"
              :disabled="false"
              :show-file-list="false"
              :m-props="{ urlObj: qrcodeImg, urlStr: 'url' }"
              :accept="uploadAccept"
              :before-upload="beforeImgUpload"
              :http-request="httpRequest"
            >
              <div v-loading="file_loading" class="tip-box">
                <div class="tip-uploader">
                  <icon-font icon="el-icon-plus" />
                </div>
                <p>添加图片</p>
                <p>（最多9张）</p>
              </div>
            </m-upload>
            <div v-for="(item, idx) in reason_imgs" :key="idx" v-viewer class="img-item">
              <el-image v-if="edit" class="delete-btn" :src="delete_img" @click.stop="deleteImgItem(idx)" />
              <el-image :fit="fitTypeFill" style="width: 134px; height: 82px;" :src="item" class="avatar" />
            </div>
          </div>
        </el-form-item>
      </el-form>
    </section>
  </div>
</template>

<script>
import { commonEnum } from '@api/m_mall_web_v1';
import { fileUpload } from '@const/aggreationCentApi';
export default {
  name: 'ReturnExchangeReason',
  props: {
    isExchange: {
      default: false,
      type: Boolean
    },
    edit: {
      default: true,
      type: Boolean
    },
    required: {
      default: true,
      type: Boolean
    },
    reasonSel: {
      default: '',
      type: String
    },
    reasonText: {
      default: '',
      type: String
    },
    reasonImgs: {
      default: () => [],
      type: Array
    }
  },
  data() {
    return {
      fitTypeFill: 'cover',
      uploadAccept: 'image/jpg,image/png,image/jpeg',
      delete_img: require('@assets/icon/beforeSettle/error.png'),
      uploadApi: fileUpload,
      reason_sel: this.reasonSel,
      reason_text: this.reasonText,
      return_reason: [],
      reason_imgs: this.reasonImgs,
      file_loading: false,
      qrcodeImg: {
        url: ''
      }
    };
  },
  watch: {
    reasonText(val) {
      this.reason_text = val;
    },
    reasonSel(val) {
      this.reason_sel = val;
    },
    'qrcodeImg.url'(val) {
      if (!val) return;
      if (this.reason_imgs.length === 9) {
        this.$message.warning(`最多只可以上传9张图片!`);
        return;
      }
      console.log(val);
      this.reason_imgs.push(val);
      this.$emit('update:reasonImgs', this.reason_imgs);
      this.qrcodeImg.url = '';
    },
    reasonImgs(val) {
      this.reason_imgs = val;
    }
  },
  created() {
    this.getReturnReason();
  },
  methods: {
    onChangeReasonSel(val) {
      this.$emit('update:reasonSel', val);
      this.$emit('reasonName', this.return_reason.find(item => item.enumKey === val).enumVal);
    },
    onChangeReasonText(val) {
      this.$emit('update:reasonText', val);
    },
    getReturnReason() {
      this.$axios({
        method: 'post',
        url: commonEnum,
        data: { indexCode: 'returnReason' }
      }).then(res => {
        this.return_reason = res.data.payload || [];
      });
    },
    deleteImgItem(i) {
      this.reason_imgs.splice(i, 1);
    },
    beforeImgUpload(file) {
      const isImg = this.uploadAccept.includes(file.type.toLowerCase());
      const isLt5M = file.size / 1024 / 1024 <= 5;
      console.log(isLt5M);
      console.log(file.size);
      console.log(file.size / 1024 / 1024);
      if (!isImg) {
        this.$message.error('上传文件只支持JPG/PNG格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
        return false;
      }
      if (this.reason_imgs.length === 9) {
        this.$message.error('最多只可以上传9张图片!');
        return false;
      }
      return true;
    },
    httpRequest(data) {
      this.file_loading = true;
      let fd = new FormData();
      fd.append('file', data.file);
      this.$axios({
        method: 'post',
        url: this.uploadApi,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      })
        .then(res => {
          const { code, payload, msg } = res.data;
          if (!Number(code)) {
            this.reason_imgs.push(payload);
            this.$emit('update:reasonImgs', this.reason_imgs);
            this.$message.success('上传成功');
          } else {
            this.$message.error(msg);
          }
        })
        .finally(() => {
          this.file_loading = false;
        });
    }
  }
};
</script>

<style lang="less">
.return-exchange-reason {
  background-color: #fff;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  .imgs-function {
    margin-left: -40px;
    display: flex;
    flex-wrap: wrap;
    .img-item {
      width: 134px;
      height: 82px;
      margin: 10px 0 0 40px;
      position: relative;
      .delete-btn {
        position: absolute;
        z-index: 1;
        right: -10px;
        top: -10px;
        width: 24px;
        height: 24px;
        &:hover {
          cursor: pointer;
        }
      }
    }
    .dialog-upload {
      margin: 10px 0 0 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 134px;
      height: 82px;
      border: 1px solid #ccc;
      .el-upload {
        height: 100%;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .tip-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        p {
          font-size: 12px;
          line-height: 1;
        }
        .tip-uploader {
          font-size: 20px;
          color: #2371c5;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-bottom: 10px;
        }
      }
    }
  }
  .el-textarea {
    width: 80%;
    .el-textarea__inner {
      resize: none;
      padding-bottom: 30px;
    }
  }
  header {
    padding: 12px 16px;
    border-bottom: 1px solid #eef0f5;
    display: flex;
  }
  section {
    padding: 20px 16px;
    min-height: 350px;
  }
}
</style>
